package com.sicilin.system.login.service;

import com.sicilin.common.exception.BusinessException;
import com.sicilin.common.exception.ServiceException;
import com.sicilin.dao.UserDao;
import com.sicilin.system.login.dto.LoginUser;
import com.sicilin.system.user.Admin;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true,propagation = Propagation.REQUIRED)
public class LoginService {

    @Autowired(required = false)
    private UserDao userDao;

    @Autowired
    private Admin admin;

    public boolean login(String username, String password)throws ServiceException,BusinessException{
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject currentUser = SecurityUtils.getSubject();
        if (!currentUser.isAuthenticated()){
            //使用shiro来验证
            token.setRememberMe(true);
            currentUser.login(token);//验证角色和权限

            LoginUser loginUser = new LoginUser();
            if(admin.getAccount().equals(username)){
                BeanUtils.copyProperties(admin,loginUser);
            }else {
                loginUser = this.findUserByAccount(username);
            }
            currentUser.getSession().setAttribute("loginUser",loginUser);
        }
        return true;
    }

    public LoginUser getCurrentUser(){
        Subject currentUser= SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        LoginUser user = (LoginUser)session.getAttribute("loginUser");
        return user;
    }

    public void logout(){
        SecurityUtils.getSubject().logout();
    }


    public LoginUser findUserByAccount(String account){
        LoginUser user = userDao.findLoginUserByAccount(account);
        if(user.getRoles().contains(null)){user.getRoles().remove(null);}
        if(user.getAuths().contains(null)){user.getRoles().remove(null);}
        return user;
    }

    public boolean isAdmin(){
        LoginUser loginUser = this.getCurrentUser();
        if(admin.getAccount().equals(loginUser.getAccount())){
            return true;
        }
        return false;
    }
}
